<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="物业公司" prop="propertyManagementCompany">
              <el-input v-model="queryParams.propertyManagementCompany" placeholder="请输入物业公司" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="项目名称" prop="projectName">
              <el-input v-model="queryParams.projectName" placeholder="请输入项目名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <div style="text-align: right">
          <el-button type="warning" icon="Download" @click="handleExport"> 导出 </el-button>
          <el-button plain icon="Plus" @click="handleAdd">新增</el-button>
          <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()">删除</el-button>
        </div>
      </template>

      <el-table v-loading="loading" :data="tenementbasicInfoList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column v-if="false" label="主键标识" align="center" prop="id" />
        <el-table-column label="序号" align="center">
          <template #default="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="物业公司" align="center" prop="propertyManagementCompany" />
        <el-table-column label="项目名称" align="center" prop="projectName" />
        <el-table-column label="项目面积" align="center" prop="projectArea" />
        <el-table-column label="联&nbsp;&nbsp;系&nbsp;&nbsp;人" align="center" prop="associate" />
        <el-table-column label="物业费标准" align="center" prop="propertyCostStandard" />
        <el-table-column label="保安人数" align="center" prop="quantitySecurity" />
        <el-table-column label="保洁人数" align="center" prop="quantityCleaning" />
        <el-table-column label="保绿人数" align="center" prop="quantityGreenConservation" />
        <el-table-column label="保修人数" align="center" prop="warrantyQuantity" />
        <el-table-column label="客服人数" align="center" prop="customerServiceNumber" />
        <el-table-column label="其他人数" align="center" prop="otherNumber" />
        <el-table-column label="合计人数" align="center" prop="totalNumberOfPeople" />
        <el-table-column label="总面积/总人数" align="center" prop="totalNumberOfPeoplePerPerson" />
        <el-table-column label="操作" width="120" fixed="right" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="编辑" placement="top">
              <el-button type="primary" link @click="handleUpdate(scope.row)">编辑</el-button>
            </el-tooltip>
            <el-tooltip content="详情">
              <el-button type="primary" link @click="handleDetail(scope.row)">详情</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>
    <!-- 添加或修改物业基础信息对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="1200px" append-to-body>
      <div class="kuaicenter">
        <div class="kuai"></div>
        <h2>基础信息</h2>
      </div>
      <el-form ref="basicInfoFormRef" :model="basicInfo.form" :rules="basicInfo.rules" label-width="100px">
        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="物业公司" prop="propertyManagementCompany">
              <el-input v-model="basicInfo.form.propertyManagementCompany" placeholder="请输入物业公司" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="项目名称" prop="projectName">
              <el-input v-model="basicInfo.form.projectName" placeholder="请输入项目名称" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="项目面积" prop="projectArea">
              <el-input v-model="basicInfo.form.projectArea" placeholder="请输入项目面积" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="联&nbsp;&nbsp;系&nbsp;&nbsp;人" prop="associate">
              <el-input v-model="basicInfo.form.associate" placeholder="请输入联系人" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="联系方式" prop="contactInformation">
              <el-input v-model="basicInfo.form.contactInformation" placeholder="请输入联系方式" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="物业费标准" prop="propertyCostStandard">
              <el-input :controls="false" v-model="basicInfo.form.propertyCostStandard" placeholder="请输入物业费标准" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="物业费用" prop="propertyExpenses">
              <el-input v-model="basicInfo.form.propertyExpenses" disabled placeholder="系统自动计算" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="电费标准" prop="electricityRateStandard">
              <el-input :controls="false" v-model="basicInfo.form.electricityRateStandard" placeholder="请输入电费标准" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="水费标准" prop="waterTariff">
              <el-input :controls="false" v-model="basicInfo.form.waterTariff" placeholder="请输入水费标准" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="kuaicenter">
        <div class="kuai"></div>
        <h2>人员配置</h2>
      </div>
      <el-form ref="staffingFormRef" :model="staffing.form" :rules="staffing.rules" label-width="100px">
        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="保安人数" prop="quantitySecurity">
              <el-input v-model="staffing.form.quantitySecurity" placeholder="请输入保安人数" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="保安配比" prop="securityRatio">
              <el-input v-model="staffing.form.securityRatio" disabled placeholder="系统自动生成" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="保洁人数" prop="quantityCleaning">
              <el-input v-model="staffing.form.quantityCleaning" placeholder="请输入保洁人数" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="保洁配比" prop="cleaningRatio">
              <el-input v-model="staffing.form.cleaningRatio" disabled placeholder="系统自动生成" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="保绿人数" prop="quantityGreenConservation">
              <el-input v-model="staffing.form.quantityGreenConservation" placeholder="请输入保绿人数" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="保绿配比" prop="greenRetainingRatio">
              <el-input v-model="staffing.form.greenRetainingRatio" disabled placeholder="系统自动生成" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="保修人数" prop="warrantyQuantity">
              <el-input v-model="staffing.form.warrantyQuantity" placeholder="请输入保修人数" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="保修配比" prop="warrantyRatio">
              <el-input v-model="staffing.form.warrantyRatio" disabled placeholder="系统自动生成" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="客服人数" prop="customerServiceNumber">
              <el-input v-model="staffing.form.customerServiceNumber" placeholder="请输入客服人数" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="客服配比" prop="customerServiceRatio">
              <el-input v-model="staffing.form.customerServiceRatio" disabled placeholder="系统自动生成" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="其他人数" prop="otherNumber">
              <el-input v-model="staffing.form.otherNumber" placeholder="请输入其他人数" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="其他配比" prop="otherRatio">
              <el-input v-model="staffing.form.otherRatio" disabled placeholder="系统自动生成" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="合计人数" prop="totalNumberOfPeople">
              <el-input v-model="staffing.form.totalNumberOfPeople" disabled placeholder="系统自动生成" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="人员配比" prop="personnelRatio">
              <el-input v-model="staffing.form.personnelRatio" disabled placeholder="系统自动生成" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template v-if="dialog.type !== 'detail'" #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">保 存</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="TenementbasicInfo" lang="ts">
import {
  listTenementbasicInfo,
  getTenementbasicInfo,
  delTenementbasicInfo,
  addTenementbasicInfo,
  updateTenementbasicInfo
} from '@/api/zichanguanli/tenementbasicInfo';
import { TenementbasicInfoVO } from '@/api/zichanguanli/tenementbasicInfo/types';
import { getPersonnelAllocation, addPersonnelAllocation, updatePersonnelAllocation } from '@/api/zichanguanli/personnelAllocation';
import { validateNumber, validateInteger } from '@/utils/formRules';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const tenementbasicInfoList = ref<TenementbasicInfoVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const basicInfoFormRef = ref<ElFormInstance>();
const staffingFormRef = ref<ElFormInstance>();

const dialog = reactive({
  visible: false,
  title: '',
  type: null
});

const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  propertyManagementCompany: '',
  projectName: ''
});

const data = reactive({
  basicInfo: {
    form: {
      id: undefined,
      propertyManagementCompany: undefined,
      projectName: undefined,
      projectArea: undefined,
      associate: undefined,
      contactInformation: undefined,
      propertyCostStandard: undefined,
      propertyExpenses: undefined,
      electricityRateStandard: undefined,
      waterTariff: undefined
    },
    rules: {
      id: [{ required: true, message: '主键标识不能为空', trigger: 'blur' }],
      propertyManagementCompany: [{ required: true, message: '物业公司不能为空', trigger: 'blur' }],
      projectName: [{ required: true, message: '项目名称不能为空', trigger: 'blur' }],
      projectArea: [
        { required: true, message: '项目面积不能为空', trigger: 'blur' },
        { validator: validateNumber, trigger: 'blur' }
      ],
      associate: [{ required: true, message: '联系人不能为空', trigger: 'blur' }],
      contactInformation: [
        { required: true, message: '联系方式不能为空', trigger: 'blur' },
        {  required: true, message: '请填写正确的手机号码', trigger: 'change' }
      ],
      propertyCostStandard: [{ required: true, message: '物业费标准不能为空', trigger: 'blur' }],
      propertyExpenses: [
        { required: true, message: '物业费用不能为空', trigger: 'blur' },
        { validator: validateNumber, trigger: 'blur' }
      ],
      electricityRateStandard: [{ required: true, message: '电费标准不能为空', trigger: 'blur' }],
      waterTariff: [{ required: true, message: '水费标准不能为空', trigger: 'blur' }]
    }
  },
  staffing: {
    form: {
      id: undefined,
      propertyBasicInfoId: undefined,
      quantitySecurity: undefined,
      securityRatio: undefined,
      quantityCleaning: undefined,
      cleaningRatio: undefined,
      quantityGreenConservation: undefined,
      greenRetainingRatio: undefined,
      warrantyQuantity: undefined,
      warrantyRatio: undefined,
      customerServiceNumber: undefined,
      customerServiceRatio: undefined,
      otherNumber: undefined,
      otherRatio: undefined,
      totalNumberOfPeople: undefined,
      personnelRatio: undefined
    },
    rules: {
      quantitySecurity: [
        { required: true, message: '保安人数不能为空', trigger: 'blur' },
        { validator: validateInteger, trigger: 'blur' }
      ],
      quantityCleaning: [
        { required: true, message: '保洁人数不能为空', trigger: 'blur' },
        { validator: validateInteger, trigger: 'blur' }
      ],
      quantityGreenConservation: [
        { required: true, message: '保绿人数不能为空', trigger: 'blur' },
        { validator: validateInteger, trigger: 'blur' }
      ],
      warrantyQuantity: [
        { required: true, message: '保修人数不能为空', trigger: 'blur' },
        { validator: validateInteger, trigger: 'blur' }
      ],
      customerServiceNumber: [
        { required: true, message: '客服人数不能为空', trigger: 'blur' },
        { validator: validateInteger, trigger: 'blur' }
      ],
      otherNumber: [
        { required: true, message: '其他人数不能为空', trigger: 'blur' },
        { validator: validateInteger, trigger: 'blur' }
      ]
    }
  }
});

const { basicInfo, staffing } = toRefs(data);

/** 查询物业基础信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listTenementbasicInfo(queryParams.value);
  tenementbasicInfoList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  buttonLoading.value = false;
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  basicInfo.value.form = {
    id: undefined,
    propertyManagementCompany: undefined,
    projectName: undefined,
    projectArea: undefined,
    associate: undefined,
    contactInformation: undefined,
    propertyCostStandard: undefined,
    propertyExpenses: undefined,
    electricityRateStandard: undefined,
    waterTariff: undefined
  };
  staffing.value.form = {
    id: undefined,
    propertyBasicInfoId: undefined,
    quantitySecurity: undefined,
    securityRatio: undefined,
    quantityCleaning: undefined,
    cleaningRatio: undefined,
    quantityGreenConservation: undefined,
    greenRetainingRatio: undefined,
    warrantyQuantity: undefined,
    warrantyRatio: undefined,
    customerServiceNumber: undefined,
    customerServiceRatio: undefined,
    otherNumber: undefined,
    otherRatio: undefined,
    totalNumberOfPeople: undefined,
    personnelRatio: undefined
  };
  basicInfoFormRef.value?.resetFields();
  staffingFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: TenementbasicInfoVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  buttonLoading.value = false;
  dialog.title = '添加物业服务信息';
  dialog.type = 'add';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: TenementbasicInfoVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getTenementbasicInfo(_id);
  basicInfo.value.form = res.data.propertyBasicInfoVo;
  staffing.value.form = res.data.propertyPersonnelAllocationVo;
  dialog.visible = true;
  dialog.title = '修改物业服务信息';
  dialog.type = 'update';
};

const handleDetail = async (row?: TenementbasicInfoVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getTenementbasicInfo(_id);
  basicInfo.value.form = res.data.propertyBasicInfoVo;
  staffing.value.form = res.data.propertyPersonnelAllocationVo;

  dialog.visible = true;
  dialog.title = '物业服务项目详情';
  dialog.type = 'detail';
};
/** 提交按钮 */
const submitForm = async () => {
  const basicInfoFormValidate = await basicInfoFormRef.value?.validate();
  const staffingFormValidate = await staffingFormRef.value?.validate();

  if (basicInfoFormValidate && staffingFormValidate) {
    try {
      buttonLoading.value = true;

      if (dialog.type === 'add') {
        const datas = {
          propertyBasicInfoBo: basicInfo.value.form,
          propertyPersonnelAllocationBo: staffing.value.form
        };
        await addTenementbasicInfo(datas);
      } else if (dialog.type === 'update') {
        const datas = {
          propertyBasicInfoBo: basicInfo.value.form,
          propertyPersonnelAllocationBo: staffing.value.form
        };
        await updateTenementbasicInfo(datas);
      }

      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    } catch (err) {
      proxy?.$modal.msgSuccess('操作失败');
    } finally {
      buttonLoading.value = false;
    }
  }
};

/** 删除按钮操作 */
const handleDelete = async (row?: TenementbasicInfoVO) => {
  const _ids = ids.value;
  const selectedBasic = [];
  tenementbasicInfoList.value.map((item) => _ids.includes(item.id) && selectedBasic.push(item.projectName));
  await proxy?.$modal.confirm('确定删除所选的信息吗').finally(() => (loading.value = false));
  await delTenementbasicInfo(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'zichanguanli/tenementbasicInfo/export',
    {
      ...queryParams.value
    },
    `tenementbasicInfo_${new Date().getTime()}.xlsx`
  );
};

// 添加watch来监听人数变化并计算总人数和配比
watch(
  [
    () => staffing.value.form.quantitySecurity,
    () => staffing.value.form.quantityCleaning,
    () => staffing.value.form.quantityGreenConservation,
    () => staffing.value.form.warrantyQuantity,
    () => staffing.value.form.customerServiceNumber,
    () => staffing.value.form.otherNumber,
    () => basicInfo.value.form.projectArea
  ],
  ([security, cleaning, green, warranty, customer, other, area]) => {
    // 确保所有值都转换为数字，如果为 undefined 或 null 则默认为 0
    const securityNum = Number(security || 0);
    const cleaningNum = Number(cleaning || 0);
    const greenNum = Number(green || 0);
    const warrantyNum = Number(warranty || 0);
    const customerNum = Number(customer || 0);
    const otherNum = Number(other || 0);
    const projectAreaNum = Number(area || 0);

    // 计算总人数
    const total = securityNum + cleaningNum + greenNum + warrantyNum + customerNum + otherNum;
    staffing.value.form.totalNumberOfPeople = total;

    // 计算各项配比
    staffing.value.form.securityRatio = securityNum !== 0 ? (projectAreaNum / securityNum).toFixed(1) : '0.0';
    staffing.value.form.cleaningRatio = cleaningNum !== 0 ? (projectAreaNum / cleaningNum).toFixed(1) : '0.0';
    staffing.value.form.greenRetainingRatio = greenNum !== 0 ? (projectAreaNum / greenNum).toFixed(1) : '0.0';
    staffing.value.form.warrantyRatio = warrantyNum !== 0 ? (projectAreaNum / warrantyNum).toFixed(1) : '0.0';
    staffing.value.form.customerServiceRatio = customerNum !== 0 ? (projectAreaNum / customerNum).toFixed(1) : '0.0';
    staffing.value.form.otherRatio = otherNum !== 0 ? (projectAreaNum / otherNum).toFixed(1) : '0.0';
    staffing.value.form.personnelRatio = total !== 0 ? (projectAreaNum / total).toFixed(1) : '0.0';
  },
  { deep: true }
);

// 监听项目面积和物业费标准的变化，自动计算物业费用
watch(
  [() => basicInfo.value.form.projectArea, () => basicInfo.value.form.propertyCostStandard],
  ([area, standard]) => {
    if (area && standard) {
      // 将字符串转换为数字并计算
      const areaNum = Number(area|| 0);
      const standardNum = Number(standard|| 0);
      // 计算物业费用并保留两位小数
      basicInfo.value.form.propertyExpenses = (areaNum * standardNum).toFixed(2) || "0.00";
    } else {
      // 如果任一值为空，则清空物业费用
      basicInfo.value.form.propertyExpenses = '';
    }
  },
  { immediate: true } // 立即执行一次
);

onMounted(() => {
  getList();
});
</script>
